<template>
  <div class="attach">
    <div v-show="currentAudit" class="header" style="align-items: center">
      <p style="margin-right: 30px"><strong>项目编号：</strong>{{ projectBuild.hatchProjectNo }}</p>
      <p style="margin-right: 30px"><strong>项目名称：</strong>{{ projectBuild.hatchProjectName }}</p>
      <!-- <p ><a-button type="primary" @click="reload(null)">刷新</a-button></p> -->
    </div>
    <div class="content">
      <div class="projectFile">
        <div class="title">其他附件</div>
        <div class="otherAttach">
          <div class="upload-control" style="display: flex">
            <ht-upload
              class="upload-demo"
              multiple
              dbKey="Trd"
              busField="HatchProject"
              :busKey="projectBuildId"
              :disabled="!otherCanEdit"
              busType="other"
              ftpKey="ftp"
              v-model="otherAttachList"
            >
              <el-button size="small" type="primary" style="height: 30px; width: 85px" v-bind:disabled="!otherCanEdit">
                <span style="font-size: 14px">上传</span></el-button
              >
            </ht-upload>
            <a-button
              type="primary"
              v-bind:disabled="!downloadAndViewOther"
              @click="otherDownLoadBatch(0)"
              style="margin-left: 10px"
              >下载</a-button
            >
            <a-button
              style="width: auto"
              type="primary"
              v-bind:disabled="!downloadAndViewOther"
              @click="otherDownLoadBatch(1)"
              >一键打包下载</a-button
            >
            <a-button class="default" @click="othersDeleteBatch" v-bind:disabled="!otherCanEdit">删除</a-button>
          </div>
          <a-table
            :row-selection="{
              selectedRowKeys: otherAttachSelectedIds,
              onChange: otherAttachSelected,
              getCheckboxProps: (record) => ({
                props: {
                  disabled: !(!record.status || record.status == 'success'),
                  name: record.status,
                },
              }),
            }"
            :columns="otherAttachColumns"
            :data-source="otherAttachDataList"
            bordered
            :pagination="false"
          >
            <template slot="name" slot-scope="text, record">
              <a @click="showAttach(record.key, record.uploader, record.name, true, 'other')">{{ record.name }}</a>
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import $ from 'jquery'
import '@/utils/upload.install.js'
import '@/config/hteupload.install.js'
import { getAction, postAction, getActionAsync, uploadAttach, getAttaches,previewAttach } from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { formatFileSize, endWith, strNotNull } from '@/utils/common.js'
import { Modal } from 'ant-design-vue'
const otherAttachColumns = [
  {
    title: '附件名称',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '附件大小',
    dataIndex: 'size',
    width: '15%',
  },
  {
    title: '上传时间',
    dataIndex: 'time',
    width: '20%',
  },
  {
    title: '上传者',
    dataIndex: 'uploaderName',
    width: '20%',
  },
]
const FTP_KEY = 'ftp'
export default {
  components: {},
  data() {
    return {
      projectBuildId: '',
      projectBuild: {},
      //其他附件字典配置
      otherAttaches: [],

      oldDrawingCodes: ['G101', 'G201', 'G301', 'G401', 'G501', 'G603', 'G703'],
      otherAttachList: [],
      otherAttachDataList: [],
      otherAttachColumns,
      otherAttachSelectedIds: [], // Check here to configure the default column
      loading: false,
      attach: {
        getProjectBuildVOWithProjectManagers: '/hatchProject/getProjectBuildVOWithProjectManagers',
        getProjectBuildAttachCodeInfos: '/projectBuild/getProjectBuildAttachCodeInfos',
        downLoadBatch: '/common/downLoadBatch',
        deleteBatch: '/common/deleteBatch',
        getAttachInfo: '/tp/attach/getAttaches',
        logAttachAdd: '/projectChange/logAttachAdd',
        logAttachDelete: '/projectChange/logAttachDelete',
      },
      url: {
        getRequiredAttachCode: '/projectBuild/getRequiredAttachCode',
        codeInfo: '/manage/codeInfo/list',
      },
      canEdit: false,
      otherCanEdit: false, //其他附件可编辑
      normalCanEdit: false, //通用附件可编辑
      currentAudit: false,
      downloadAndViewProject: false,
      downloadAndViewOther: false,
      changeId: this.$route.query.changeId,
      canDoSave: this.$route.query.canDoSave == 'true' ? true : false,

      fileList: [],
      fileQueryList: [],
    }
  },
  mounted() {
    this.projectBuildId = this.$route.query.hatchProjectBuildId
    var currentAudit = this.$route.query.currentAudit
    this.currentAudit = currentAudit == 'true' ? true : false
    this.initData()
  },
  created () {
    this.projectBuildId = this.$route.query.hatchProjectBuildId
  },
  computed: {},
  watch: {
    otherAttachList: {
      deep: true,
      handler(fileList) {
        this.otherAttachDataListFresh()
      },
    },
  },
  methods: {
    showAttach(id, uploader, fileName, autoDownload, type, ftpKey = 'ftp') {
      if (!this.checkPermisson(uploader, type)) {
        if (type == 'main' && this.changeId) {
          this.$message.warning('仅有项目经理可以查看变更中的项目附件')
        } else {
          this.$message.warning('仅有该附件上传人、审批人、抄送人、项目经理、管理员可以查看!')
        }
        return
      }
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        if (autoDownload) {
          this.doDownLoadBatch(id)
          return
        }
        this.$message.warning('该附件类型不支持预览，请下载附件查看')
        return
      }
      let params={
        id:id,
        ftpKey:'ftp'
      };
      previewAttach(params).then(result=>{
        const url=URL.createObjectURL(result)
        if (this.projectBuild.projectClass == '40' || this.projectBuild.projectClass == '61') {
          window.open(process.env.BASE_URL+'/pdf/web/normalViewer.html?file=' + url)
        } else {
          window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
        }
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },
    doDownLoadBatch(attachIds,ftpKey = 'ftp') {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame')
      var href =
        this.API_BASE_URL +
        this.attach.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey='+ftpKey+'&token=' +
        Vue.ls.get(ACCESS_TOKEN)
      iframe.src = href
    },
    checkPermisson(uploader, type) {
      var currUser = Vue.ls.get(USER_INFO).username
      if (type == 'other' && (uploader == currUser || this.downloadAndViewOther)) {
        return true
      }
      return false
    },
    otherAttachDataListFresh() {
      let vm = this
      this.otherAttachDataList = []
      let index = 0
      this.otherAttachList.forEach((item) => {
        var size = formatFileSize(item.size)
        this.otherAttachDataList.push({
          key: item.id || item.uid,
          name: item.fileName || item.name,
          size: size,
          time: item.uploadTime,
          uploader: item.uploader,
          uploaderName: item.uploaderName,
          status: item.status || 'success',
          percentage: item.percentage,
          uid: item.uid,
        })
      })
    },
    start() {
      this.loading = true
      setTimeout(() => {
        this.loading = false
        this.otherAttachSelectedIds = []
      }, 1000)
    },
    otherAttachSelected(selectedRowKeys) {
      this.otherAttachSelectedIds = selectedRowKeys
    },
    otherDownLoadBatch(status) {
      if (status == 1) {
        let ids = []

        this.otherAttachList.map((item) => {
          ids.push(item.id)
        })
        this.doDownLoadBatch(ids)
        return
      }
      if (this.otherAttachSelectedIds != null && this.otherAttachSelectedIds.length > 0) {
        this.doDownLoadBatch(this.otherAttachSelectedIds)
      } else {
        this.$message.warning('请选择要下载的其它附件')
      }
    },
    othersDeleteBatch() {
      if (this.otherAttachSelectedIds != null && this.otherAttachSelectedIds.length > 0) {
        let attachCodes = []
        this.delFiles(this.otherAttachSelectedIds.join(','), attachCodes.join(','), this.othersDeleteFileList)
      } else {
        this.$message.warning('请选择要删除的其它附件')
      }
    },
    othersDeleteFileList() {
      let vm = this

      this.otherAttachSelectedIds.forEach((item) => {
        let index = -1
        if (!item.status || item.status == 'success') {
          index = this.otherAttachList.findIndex((attach) => {
            return attach.id == item
          })
        }
        if (item.status == 'fail') {
          index = this.otherAttachList.findIndex((attach) => {
            return attach.uid == item
          })
        }
        if (index != -1) {
          this.otherAttachList.splice(index, 1)
        }
      })
      this.otherAttachSelectedIds = []
    },
    delFiles(attachIds, attachCodes, callBack, ftpKey = 'ftp') {
      const that = this
      Modal.confirm({
        title: '确认删除',
        content: '此操作将删除选中附件, 是否继续?',
        onOk: function () {
          getAction(that.attach.deleteBatch, {
            attachIds: attachIds,
            busField: 'HatchProject', 
            busType: 'other',
            dbKey: 'Trd',
            ftpKey: ftpKey,
            changeId: that.changeId,
          })
            .then((res) => {
              if (res.code == 1) {
                that.$message.success('批量删除成功')

                callBack()
                //this.reload()
                // setTimeout(function () {
                //   window.location.reload()
                // }, 500)
              } else {
                that.$message.warning('批量删除失败:' + res.msg)
              }
            })
            .catch((res) => {
              that.$message.warning('批量删除失败:' + res.msg)
            })
        },
      })
    },
    getAttaches(dataDefault, vm, key) {
      key = !!key ? key : 'filelist'
      if (dataDefault.busKey && dataDefault.busField) {
        vm[key] = []
        getAttaches(dataDefault)
          .then((result) => {
            if (result.code == 1) {
              vm[key] = result.data
            } else {
              console.log(`查询附件列表失败：${result.msg}`)
            }
          })
          .catch((err) => {
            console.log(`查询附件列表失败：${err.message}`)
          })
      }
    },
    initData() {
      var vm = this
      getAction(this.attach.getProjectBuildVOWithProjectManagers, { id: this.projectBuildId })
        .then((res) => {
          if (res.code == 200) {
            var result = res.result
            if (result != null) {
              vm.projectBuild = result
              if (result.hatchProjectType != null && result.hatchProjectType.length > 0) {
                //vm.getRequiredAttachCode()

                var currUser = Vue.ls.get(USER_INFO).username
                var realname = Vue.ls.get(USER_INFO).realname
                if (
                  vm.projectBuild.createUserName === currUser  ||
                  (vm.projectBuild.leaders && vm.projectBuild.leaders.indexOf(realname) > -1) ||
                  vm.projectBuild.currentAuditUserId === currUser ||
                  (vm.projectBuild.copyForUserIds != null && vm.projectBuild.copyForUserIds.indexOf(currUser) > -1) ||
                  (vm.projectBuild.allAuditors != null && vm.projectBuild.allAuditors.indexOf(currUser) > -1)
                ) {
                  vm.otherCanEdit = true
                }

                if (vm.otherCanEdit || vm.projectBuild.downAndView) {
                  vm.downloadAndViewOther = true
                  if (vm.changeId) {
                    if (
                      (vm.projectBuild.projectManagers != null &&
                        vm.projectBuild.projectManagers.indexOf(currUser) > -1) ||
                      vm.projectBuild.projectSubTypeAdmin
                    ) {
                      vm.downloadAndViewProject = true
                    }
                  } else {
                    vm.downloadAndViewProject = true
                  }
                }
              }
            }
          } else {
            this.$message.warning('查询附件相关信息失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询附件相关信息异常:' + res.message)
        })
    },
    getRequiredAttachCode() {
      getAction(this.url.codeInfo, { type: this.projectBuild.hatchProjectType + '类必传附件' })
        .then((res) => {
          if (res.code == 200) {
            this.requiredAttachCode = res.result.records || []
            this.initAttaches(this.projectBuild.hatchProjectType)
          } else {
            this.$message.warning('查询必填附件失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询必填附件失败:' + res.message)
        })
    },
    async initAttaches(hatchProjectType) {
      var vm = this
      getAction(this.attach.getProjectBuildAttachCodeInfos, { projectType: hatchProjectType, timeNodeCode: '1' })
        .then(async (res) => {
          if (res.code == 200) {
            var result = res.result
            if (result != null) {
              let otherAttaches = []
              let mainAttaches = []
              for (let index = 0; index < result.length; index++) {
                const item = result[index]

                if (vm.requiredAttachCode != null) {
                  vm.requiredAttachCode.forEach((reqAtt) => {
                    if (reqAtt.code == item.code) {
                      item.required = true
                    }
                  })
                }
                if (item.code == 'other') {
                  otherAttaches.push(item)
                } else if (item.code == 'drawing') {
                  if (!vm.showDrawingNew) {
                    continue
                  }
                  item.ftpKey = new String(FTP_KEY)
                  //工程项目图纸附件ftp
                  if (vm.projectBuild.projectClass == '40') {
                    item.ftpKey = 'ftpDRA'
                  }

                  let ftpRes = await getActionAsync(this.url.codeInfo, {
                    type: hatchProjectType + '类立项附件FTP',
                    parentid: '1',
                    code: item.code,
                  })

                  if (ftpRes.success) {
                    if (ftpRes.result.records.length > 0) {
                      item.ftpKey = ftpRes.result.records[0].name
                    }
                  }
                } else {
                  if (vm.oldDrawingCodes.indexOf(item.code) >= 0) {
                    if (!vm.showDrawingNew) {
                      mainAttaches.push(item)
                    }
                  } else {
                    mainAttaches.push(item)
                  }
                }
              }
              vm.otherAttaches = otherAttaches
              vm.mainAttaches = mainAttaches
            }
          } else {
            this.$message.warning('查询附件字典配置失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询附件字典配置失败:' + res.message)
        })
    },
  },
}
</script>
<style lang="less" scoped>
/deep/.el-upload-list {
  display: none;
}
/deep/.anticon {
  font-size: 16px;
  vertical-align: middle;
}
.otherAttach /deep/ .ant-btn-primary,
.download-control /deep/ .ant-btn-primary {
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #1890ff;
  margin-right: 10px;
}
.otherAttach /deep/ .default,
.download-control /deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
/deep/ .ant-table-thead > tr > th {
  background: #dadee9 !important;
}
/deep/.ant-table-thead > tr:first-child > th:first-child,
/deep/ .ant-table table {
  border-radius: unset;
  line-height: 1;
}
/deep/ .ant-table-tbody .ant-table-row td {
  &:nth-child(2) {
    color: #3e8ee2;
  }
}
/deep/ .ant-table-tbody .ant-table-row td {
  padding-top: 8px;
  padding-bottom: 8px;
}
.attach {
  border: 1px solid #e6e6e6;
  background-color: #fff;
  padding-bottom: 30px;
  .header {
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    padding: 20px 0 0 20px;
  }
  .content {
    padding: 15px;
    .projectFile {
      .title {
        border-left: 3px solid #47a4fa;
        padding: 0 10px;
        .download-control {
          display: inline-block;
          margin-left: 10px;
        }
      }
    }
    ul {
      list-style: none;
      padding: 15px 0;
      border-bottom: 1px solid #f7f7f7;
      li {
        padding: 15px !important;
        border: 1px solid #e8e8e8;
        border-radius: 6px;
        margin-bottom: 15px;
        display: flex;
        align-items: flex-start;
      }
      .upload-demo {
        display: flex;
        /deep/ .el-upload {
          margin-right: 10px;
        }
      }
    }
    .infoTips {
      background: #e6f7ff;
      border: 1px solid #aee1ff;
      border-radius: 4px;
      margin: 20px 0;
      padding: 5px 10px;
      font-size: 12px;
      width: fit-content;
    }
    .otherAttach {
      margin-top: 20px;
      .upload-control {
        margin-bottom: 15px;
      }
    }
    .btn {
      display: flex;
      justify-content: center;
      margin-top: 30px;
    }
  }
}
</style>